import axios from 'axios';

console.log('process:', process.env.VUE_APP_BASE_URL);
const instance = axios.create({
  baseURL: process.env.VUE_APP_BASE_URL,
  timeout: 50000, // request timeout
  headers: {
    'X-Requested-With': 'XMLHttpRequest',
    'Content-Type': 'application/json',
  },
});

instance.interceptors.request.use(
  config => {
    config.headers['Access-Control-Allow-Origin'] = 'X-Requested-With';
    return config;
  },
  error => {
    console.error('request interceptors error:', error);
    return Promise.reject(error);
  },
);

instance.interceptors.response.use(
  response => {
    if (response.data) {
      const res = response.data;
      if (res.resultCode) {
        if (res.resultCode !== '200') {
          return Promise.reject(new Error(res.message || 'Error'));
        } else {
          return res;
        }
      } else if (response.status === 200) {
        return res;
      }
    }
  },
  error => {
    console.log('err' + error); // for debug
    return Promise.reject(error);
  },
);

export default instance;
